﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using ETWebApi2.Models;
using Model;
using BllFactory;
using IBLL;

namespace ETWebApi2.Controllers
{
    
    [Route("needdown"), JwtAuthActionFilter]
    public class NeedToDownLoadController : ApiController
    {

        private MyETLockContext m_db = DbContextFactory.GetDbContext();
        private ICUser_tbService m_userServer = ServiceFactory.CreatService<ICUser_tbService>();
        /// <summary>
        /// 加载初始数据以及按条件搜索数据
        /// </summary>  一开始加载未下载文件  
        /// <param name="QueryType">1-->已下载 0-->未下载</param>
        /// <param name="query"></param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetFiles(int QueryType, string query,int page,int limit)
        {
            JwtAuthObject info = new BaseClass().GetInfoByToken(Request.Headers.Authorization.Parameter);
            //info.UserId改为 35  
            CUser_tb CurrentUser = m_userServer.GetList(u => u.Id == info.UserId).FirstOrDefault();
            int startRow = (page - 1) * limit;
            if (CurrentUser.Permission.Substring(1) == "0" && CurrentUser.Down==0)
                return ObjectToJson.toJson(new { status=201,error= "您没有权限下载" });
            else
            {
                //UploadId根据这个获取客户id然后获取客户名称  
                string sql = "select ROW_NUMBER()over(order by Time desc) rnumber, Files_tb.Id as Id,Attachment as FileName,UploadUserId as UploadId,CompanyId,Time,dTime as DTime,dUserId,Files_tb.dIP from Files_tb join FileDownLoadLog_tb on FileDownLoadLog_tb.FileId=Files_tb.Id where Files_tb.IsValid=1 and FileDownLoadLog_tb.DUser=" + info.UserId;
                if (QueryType == 0)
                    sql = sql + "and dUserId = 0";
                else if (QueryType == 1) //  dUserId等于当前用户id    
                    sql = sql + "and dUserId ="+ info.UserId;
                if (!string.IsNullOrEmpty(query))
                    sql = sql + "and Attachment like '%"+query+"%'";
                List<NeddDownModel> pages = new List<NeddDownModel>();
                int total = 0;
                using (var m_db = new MyETLockContext())
                {
                    var res = m_db.Database.SqlQuery<object>(sql);
                    total = res.Count();
                    if (total > 0)
                        pages = m_db.Database.SqlQuery<NeddDownModel>(string.Format("select * from ({0}) a where rnumber between {1} and {2}", sql, startRow+1, limit * page)).ToList();
                }
                List<FilesShow> showdatas = ShowData(pages, QueryType);
                return ObjectToJson.toJson(new { status=200,data=new { total=total,rows= showdatas } });
            }
        }
        private List<FilesShow> ShowData(List<NeddDownModel> datas,int type) 
        {
            List<FilesShow> files = new List<FilesShow>();
            BaseClass bc = new BaseClass();
            for (int i = 0; i < datas.Count; i++)
            {
                FilesShow file = new FilesShow();
                file.Id = datas[i].Id;
                file.FileName = datas[i].FileName;
                file.UserName = bc.GetUserNameByUid(datas[i].UploadId);
                file.Name =bc.GetCompanyName(bc.GetCompanyIdByUid(datas[i].UploadId));
                file.IP = datas[i].dIP;

                //if (type == 1)
                file.DownloadTime = Convert.ToDateTime(datas[i].DTime).ToString("yyyy-MM-dd");
               // else
                file.Time = Convert.ToDateTime(datas[i].Time).ToString("yyyy-MM-dd");
                files.Add(file);
            }
            return files;
        }
    }
}
